package com.wxtl.service;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Service;

import com.sun.org.apache.commons.beanutils.BeanUtils;
import com.wxtl.dao.CustomerDAO;
import com.wxtl.dao.DogDAO;
import com.wxtl.entity.Customer;
import com.wxtl.entity.Dog;
import com.wxtl.entity.User;
import com.wxtl.exception.ServiceException;
import com.wxtl.util.DataGridModel;
import com.wxtl.util.ID;
import com.wxtl.util.NumberUtil;
import com.wxtl.util.Page;
import com.wxtl.util.Status;
import com.wxtl.ws.UpPackAction;

/**
 * 
 * @author hc24
 * @modify by liulin 修改custId
 */
@Service
public class CustomerService {
	private Log logger = LogFactory.getLog(CustomerService.class);

	private CustomerDAO customerDAO;
	private DogDAO dogDAO;

	public void setCustomerDAO(CustomerDAO customerDAO) {
		this.customerDAO = customerDAO;
	}

	public void setDogDAO(DogDAO dogDAO) {
		this.dogDAO = dogDAO;
	}

	/**
	 * 客户注册
	 * 
	 * @param upsp
	 * @return
	 */
	public Customer register(UpPackAction upsp) {
		Customer customer = customerDAO.queryByDog(upsp.getDogsn());
		if(customer==null)
			customer=new Customer();
		try {
			BeanUtils.copyProperties(customer,upsp);
			customer.setBizScope(upsp.getBizScope());
			customer.setEntName(upsp.getEntname());
			customer.setIndustryType(upsp.getIndustryType());
			
		} catch (Exception e) {
			logger.error(e);
			throw new ServiceException("注册失败，请联系厂商");
		}
		// 验证加密狗
		Dog dog=dogDAO.getDogBySn(upsp.getDogsn());
		if(dog==null)
			throw new ServiceException("编号为"+upsp.getDogsn()+"的加密狗不存在，请联系厂商");
		
		
		
//		if(customerDAO.queryByEntname(customer.getEntName())!=null)
//			throw new ServiceException("企业名称已经被注册");
		
		
		
		//生成客户编号和授权编号
		String custsn = ID.custId(upsp.getProvince(), upsp.getCity())+NumberUtil.format(customerDAO.getCount()+1, "00000000");
		customer.setCustsn(custsn);
		customer.setAuthsn(ID.authId()+NumberUtil.format(customerDAO.getCount()+1, "0000"));
		customer.setState(Status.CUST_STATE_NORMAL);//状态正常
		//保存客户
		customerDAO.saveOrUpdate(customer);
		
		System.out.println("注册生成新的客户:"+customer.getCustId());
		
		return customer;
	}
	
	public Page query(DataGridModel dgm,Customer customer){
		return customerDAO.query(dgm,customer);
	}
	
	public void update(Customer customer){
		customerDAO.update(customer);
	}
}
